package com.sky.service.user.Impl;


import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.user.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;


@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Value("${sky.wechat.appid}")
    private String appId;

    @Value("${sky.wechat.secret}")
    private String secret;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;

    public UserLoginVO login(UserLoginDTO dto){
        //用户微信登录，完成自动注册
        //1.去微信端获取openid
        String openId = getOpenId(dto.getCode());
        //2.根据openid找用户，检查是否存在
        if(!StringUtils.hasText(openId)){
            throw new BaseException("未获取到openId");
        }
        User user= userMapper.getByOpenId(openId);
        //3.不存在添加数据
        if (user==null){
            user = new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openId);
            userMapper.save(user);
        }
        //存在生成token
        HashMap<String, Object> param = new HashMap<>();
        param.put("openId",openId);
        param.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), param);

        //设置商家结果
        Merchant merchant = merchantMapper.selectById(1L);

        //计算方法
        String lnglat = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal cost = MapUtils.getDelivoryCost(lnglat, dto.getLocation());

        //构造返回结果
        UserLoginVO loginVO = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(cost)
                .build();
        return loginVO;
    }

    /**
     * 获取Openid
     * @param code
     * @return
     */
    private String getOpenId(String code){
        HashMap<String, String> param = new HashMap<>();
        param.put("appid",appId);
        param.put("secret",secret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        String response = HttpClientUtil.doGet(URL, param);
        log.info("微信登录返回：,{}",response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid =(String) jsonObject.get("openid");

        return openid;
    }


}




